package com.gitee.wsl.data.store.mmkv

import com.gitee.wsl.data.store.AbstractStoreServer
import com.gitee.wsl.data.store.StoreServer
import com.tencent.mmkv.MMKV
import kotlin.reflect.KClass

class MMKVStoreServer(private val kv: MMKV): AbstractStoreServer() {

    override fun <T:Any> getOrNull(key: String, type: KClass<T>): T? {
        val value : Any = when(type) {
                   Long::class     -> kv.decodeLong(key)
                   String::class      -> kv.decodeInt(key)
                   Int::class         -> kv.decodeString(key)
                   Boolean::class     -> kv.decodeBool(key)
                   Float::class      -> kv.decodeFloat(key)
                   Double::class      -> kv.decodeDouble(key)
                   else -> {
                        //getExtPreference(name, type)
                       null
                   }
               } ?:return null
        return value as T
    }

    override fun <T:Any> realPut(key: String, value: T): Unit = with(kv) {
            when (value) {
                is Long -> encode(key, value)
                is Int -> encode(key, value)
                is String -> encode(key, value)
                is Boolean -> encode(key, value)
                is Float -> encode(key, value)
                is Double -> encode(key, value)
                //is Parcelable -> encode(key, value)
                is ByteArray -> encode(key, value)
                else ->{
                } //putExtPreference(key,value)
            }
    }

    override fun realRemove(key: String){
       kv.removeValueForKey(key)
    }

    override fun isExits(key: String): Boolean {
        return  kv.containsKey(key)
    }

    companion object{
        fun get(): StoreServer = MMKVStoreServer(MMKV.defaultMMKV())
    }
}